import java.util.Arrays;

public class Candy0106_153 {
    public int candy(int[] ratings) {
        if(ratings.length == 1) return 1;
        int[] candy = new int[ratings.length];
        candy[0]=1;

        //从左向右遍历，先保证 当前孩子比左边孩子大， 至于不大的先赋值1
        for (int i = 1; i < ratings.length; i++) {
            if(ratings[i-1] >= ratings[i]) {
                candy[i] = 1;
            }
            else candy[i] = candy[i-1] +1;
        }

        //从右向左遍历，保证 当前孩子比右边孩子大， 更新当前孩子时，max(candy[i-1],candy[i]+1)很关键！！！
        for (int i = ratings.length - 1; i > 0; i--) {
            if(ratings[i-1] > ratings[i]) candy[i-1] = Math.max(candy[i-1],candy[i]+1);
        }

        return Arrays.stream(candy).sum();
    }
}
